<template>
  <div class="article-contianer">
    <van-pull-refresh
      v-model="isLoading"
      :success-text="successText"
      @refresh="onRefresh"
      success-duration="1500"
    >
      <van-list
        class="artcile-list"
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
      >
        <article-item
          v-for="(item, index) in list"
          :key="item.art_id + index"
          :article="item"
        />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from '@/api/article'
import ArticleItem from './article-item.vue'

export default {
  name: 'article-list',
  components: {
    ArticleItem
  },
  props: {
    channel: {
      type: Object,
      require: true
    }
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: '',
      error: false,
      isLoading: false,
      successText: '刷新成功'
    }
  },
  methods: {
    async onLoad() {
      try {
        const { data: { data: { results, pre_timestamp } } } = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now()
        })

        this.list.push(...results)

        this.loading = false

        if( results.length ) {
          this.timestamp = pre_timestamp
        } else {
          this.finished = true
        }

      } catch (err) {
        this.loading = false
        this.error = true
      }
    },
    async onRefresh () {
      try {
        const { data: { data: { results, pre_timestamp } } } = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now()
        })

        this.list.unshift(...results)
        this.successText = `刷新成功, 更新了${results.length}条数据`
        this.isLoading = false
      } catch (err) {
        this.successText = '刷新失败'
      }

    }
  }
}
</script>

<style lang="less" scoped>
.article-contianer {
  .artcile-list {
    height: 79vh;
    overflow: auto;
  }
}

</style>
